package gopi.labs.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class InitCloud {
	
	private Connection connection;
	private Properties properties;
	
	public void readParams() throws IOException {
		this.properties = new Properties();
		InputStream is = new FileInputStream("config.properties");
		properties.load(is);

	}
	private void connect() throws SQLException, ClassNotFoundException {

		Class.forName(this.properties.getProperty("HSQLDB_CLASS"));

		this.connection = DriverManager.getConnection(
				this.properties.getProperty("HSQLDB_URL"),
				this.properties.getProperty("HSQLDB_USER"),
				this.properties.getProperty("HSQLDB_PASSWORD"));

		this.connection.setAutoCommit(false);
	}

	

	private void disconnect() throws SQLException {
		this.connection.close();
	}
	
	private void createObjects() throws IOException, SQLException
	{
		FileInputStream fs = new FileInputStream("hsqldb_ddl.sql");
		Statement stmt = this.connection.createStatement();
		InputStreamReader isr = new InputStreamReader(fs);
		
		StringBuffer str = new StringBuffer();
		
		while(isr.ready()) {
			char ch = (char) isr.read();
			if(ch == ';') {
				System.out.println(str.toString());
				stmt.execute(str.toString());
				str.delete(0, str.toString().length());
			}
			else {
				str.append(ch);
			}
		}
		isr.close();
		stmt.close();
		this.connection.commit();
		
	}
	public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException
	{
		InitCloud init = new InitCloud();
		init.readParams();
		init.connect();
		init.createObjects();
		init.disconnect();
	}
}
